package com.mtzqc.common.kt

import com.trello.rxlifecycle4.LifecycleProvider
import com.trello.rxlifecycle4.LifecycleTransformer
import com.trello.rxlifecycle4.android.ActivityEvent
import com.trello.rxlifecycle4.android.FragmentEvent
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable

fun Disposable?.safeClose() {
    this?.takeIf { !it.isDisposed }?.dispose()
}

fun <T : Any> Observable<T>.bindLife(
    provider: LifecycleProvider<ActivityEvent>,
    main: Boolean = true,
    event: ActivityEvent = ActivityEvent.DESTROY
): Observable<T> {
    return this.observeOnMain(provider.bindUntilEvent(event), main)
}

fun <T : Any> Observable<T>.bindLife(
    provider: LifecycleProvider<FragmentEvent>,
    main: Boolean = true,
    event: FragmentEvent = FragmentEvent.DESTROY_VIEW
): Observable<T> {
    return this.observeOnMain(provider.bindUntilEvent(event), main)
}

private fun <T : Any> Observable<T>.observeOnMain(
    transformer: LifecycleTransformer<T>,
    main: Boolean
): Observable<T> {
    return this.compose(transformer).let {
        if (main) it.observeOn(AndroidSchedulers.mainThread()) else it
    }
}
